package com.uchedao.vehicledetection.view.carlist;

/**
 * Created by ZhangZhanghua on 2015/8/28 0028.
 */

import android.app.ProgressDialog;
import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.uchedao.mybaselibrary.utils.LogUtil;
import com.uchedao.mybaselibrary.utils.Md5Util;
import com.uchedao.vehicledetection.application.UCheDaoApplication;
import com.uchedao.vehicledetection.model.VinCarInfor;
import com.uchedao.vehicledetection.view.carlist.Entity.CarBrand;
import com.uchedao.vehicledetection.view.carlist.Entity.CarModel;
import com.uchedao.vehicledetection.view.carlist.Entity.CarSeries;
import com.uchedao.vehicledetection.view.carlist.Entity.IndexSelectItem;
import com.uchedao.vehicledetection.view.carlist.db.CarDbHelper;
import com.uchedao.vehicledetection.view.carlist.http.AsyncHttpBaseAPI;
import com.uchedao.vehicledetection.view.carlist.http.AsyncHttpResponseHandler;
import com.uchedao.vehicledetection.view.carlist.http.HttpFailureException;
import com.uchedao.vehicledetection.view.carlist.m_interface.MyInterface;

import java.util.ArrayList;

public class CarDbUtil {
    public static final String VERSION = "1.0";
    public static final String URL_GET_TOKEN = "auth.getAccessToken";
    public static final String URL_BRAND = "var.getCarBrandOption";
    public static final String URL_SERIES = "var.getCarSeriesOption";
    public static final String URL_MODEL = "var.getCarModelOption";

    private static String HOST = "http://appserv.273.cn/";
    private static String API_KEY = "6a493a592c1adf48b8879c52d89f8c81";
    private static String API_SECRET = "c6f31fa404cf59eeac431a41455a80aa";

    private static AsyncHttpBaseAPI baseAPI;

    private static String token;

    private static CarDbHelper carDbHelper;

    private static ArrayList<IndexSelectItem> items;

    private static ArrayList<CarBrand> brandList;

    private static ArrayList<CarSeries> seriesList;

    private static ArrayList<CarModel> modelList;

    private static MyInterface mInterface;

    private static ProgressDialog dialog;

    private static long time;
    private static boolean temp = false;

    public interface CarDbUtilListener {
        public void action(int action, String msg);
    }


    public interface CarVinListener {
        public void onSuccess(VinCarInfor[] data);

        public void onFail();
    }

    /**
     * 更新车型库
     *
     * @param context
     */
    public static void updateDb(Context context ,MyInterface myInterface) {
        mInterface =  myInterface;
        baseAPI = new AsyncHttpBaseAPI(UCheDaoApplication.getContext());
        carDbHelper = CarDbHelper.getInstance(context);
        items = new ArrayList<IndexSelectItem>();
        brandList = new ArrayList<CarBrand>();
        seriesList = new ArrayList<CarSeries>();
        modelList = new ArrayList<CarModel>();
//        showUpdateDbDialog(context);
        items.clear();

        new Thread(updateDbRunnable).start();
    }

    /**
     * 更新车型库
     *
     * @param context
     */
    public static void updateDb(Context context) {
        baseAPI = new AsyncHttpBaseAPI(UCheDaoApplication.getContext());
        carDbHelper = CarDbHelper.getInstance(context);
        items = new ArrayList<IndexSelectItem>();
        brandList = new ArrayList<CarBrand>();
        seriesList = new ArrayList<CarSeries>();
        modelList = new ArrayList<CarModel>();
        items.clear();
        new Thread(updateDbRunnable).start();
    }

    private static boolean running = true;
    private static Runnable updateDbRunnable = new Runnable() {

        @Override
        public void run() {

            time = System.currentTimeMillis();
            LogUtil.e("net operate start");

            if (TextUtils.isEmpty(token)) {
                getToken(new GetTokenListener() {

                    @Override
                    public void onSuccess() {
                        getBrand();
                    }
                });
            } else {
                getBrand();
            }
        }
    };

    private static Runnable taskRunnable = new Runnable() {

        @Override
        public void run() {

            while (running) {
                if (baseAPI.getActiveCount() < baseAPI.getMaxCount() - 1 && items.size() > 0) {
                    IndexSelectItem item = items.remove(0);

                    if (item instanceof CarBrand) {
                        getSeries(((CarBrand) item).getId());

                    } else if (item instanceof CarSeries) {
                        getModel(((CarSeries) item).getId());
                    }

                } else if (baseAPI.getActiveCount() == 0 && items.size() == 0) {// 下载完成
                    LogUtil.e(" brand:" + brandList.size() + " series:" + seriesList.size() + " model:" + modelList.size());
                    running = false;
                    time = System.currentTimeMillis() - time;
                    LogUtil.e("net operate end " + time);
                    writeDB();// 写数据库
                } else {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    };

    /**
     * 写数据库
     */
    private static void writeDB() {
        LogUtil.e("db operate start");
        time = System.currentTimeMillis();
        carDbHelper.beginTransaction();

            carDbHelper.deleteAllTable();

        for (CarBrand brand : brandList) {
            carDbHelper.insertBrand(brand.getId(), brand.getName(), brand.getSpell());
        }

        for (CarSeries series : seriesList) {
            carDbHelper.insertSeries(series.getId(), series.getBrandId(), series.getName(), series.getSpell());
        }

        for (CarModel model : modelList) {
            carDbHelper.insertModel(model.getId(), model.getSeriesId(), model.getName(), model.getModelYear());
        }

        carDbHelper.setTransactionSuccessful();
        carDbHelper.endTransaction();
        time = System.currentTimeMillis() - time;
        LogUtil.e("db operate end " + time);
        mInterface.onFinish(true);
    }

    private class BrandRespone {
        @SerializedName("errorCode")
        int errorCode;
        @SerializedName("errorMessge")
        String errorMessge;

        @SerializedName("data")
        CarBrand[] data;

    }

    private class SeriesRespone {
        @SerializedName("errorCode")
        int errorCode;
        @SerializedName("errorMessge")
        String errorMessge;

        @SerializedName("data")
        CarSeries[] data;

    }


    private class ModelRespone {
        @SerializedName("errorCode")
        int errorCode;
        @SerializedName("errorMessge")
        String errorMessge;

        @SerializedName("data")
        CarModel[] data;

    }

    private class TokenRespone {
        @SerializedName("errorCode")
        int errorCode;
        @SerializedName("errorMessge")
        String errorMessge;

        @SerializedName("data")
        String data;

    }

    /**
     * 得到当前PHP格式时间戳
     *
     * @return String
     */
    private static String getPHPCurrentTime() {
        String time = String.valueOf(System.currentTimeMillis());
        return time.substring(0, time.length() - 3);
    }

    /**
     * 得到基本系统参数
     *
     * @return String
     */
    private static String getBaseParams(String url) {
        String time = getPHPCurrentTime();
        String params = "_api_time=" + time + "&_api_key=" + API_KEY;
        if (URL_GET_TOKEN.equals(url))
            params += "&_api_secret=" + Md5Util.MD5(API_SECRET + time);
        else
            params += "&_api_token=" + token;
        return params;
    }

    /**
     * 获取URL
     * @param url
     * @param params
     *
     */
    public static String getUrl(String url, String params) {
        if (params == null)
            params = "";
        return HOST + VERSION + "/" + url + "?" + getBaseParams(url) + params;
    }

    private static void error(String msg) {
        running = false;
        baseAPI.resetHttpClient();
//        ToastUtil.showToastLong(msg);
    }

    /**
     * 得到品牌
     */
    private static void getBrand() {
        String url = getUrl(URL_BRAND, "");
        baseAPI.post(url, null, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);

                BrandRespone response = new Gson().fromJson(content, BrandRespone.class);

                if (response.errorCode != 0) {// 返回错误
                    error("获取品牌数据出错 code=" + response.errorCode + " : " + response.errorMessge);
                    return;
                }

                CarBrand[] brands = response.data;

                for (CarBrand brand : brands) {
                    LogUtil.e(brand.toString());
                    items.add(brand);
                    brandList.add(brand);
                }

                running = true;
                new Thread(taskRunnable).start();
            }

            @Override
            public void onFailure(HttpFailureException error) {
                super.onFailure(error);
                error("获取品牌数据出错 error=" + error.getMessage());
            }

            @Override
            public void onFailure(HttpFailureException error, String content) {
                super.onFailure(error, content);
                error("获取品牌数据出错 error=" + error.getMessage() + " " + content);
            }

        });

    }

    private static class SeriesResponseHandler extends AsyncHttpResponseHandler {

        @Override
        public void onSuccess(String content) {
            super.onSuccess(content);
            SeriesRespone response = new Gson().fromJson(content, SeriesRespone.class);
            if (response.errorCode != 0) {// 返回错误
                error("获取车系数据出错 code=" + response.errorCode + " : " + response.errorMessge);
                return;
            }
            // "id": "380",
            // "brand_id": "53",
            // "full_spell": "pasate",
            // "text": "\u5e15\u8428\u7279",

            CarSeries[] carSeries = response.data;
            for (CarSeries series : carSeries) {
                items.add(series);
                seriesList.add(series);
            }
        }

        @Override
        public void onFailure(HttpFailureException error) {
            super.onFailure(error);
            error("获取车系数据出错 error=" + error.getMessage());
        }

        @Override
        public void onFailure(HttpFailureException error, String content) {
            super.onFailure(error, content);
            error("获取车系数据出错 error=" + error.getMessage() + " " + content);
        }

    }

    /**
     * 得到车系
     */
    private static void getSeries(int brandId) {
        String url = getUrl(URL_SERIES, "&brand_id=" + brandId);
        baseAPI.post(url, null, new SeriesResponseHandler());

    }

    private static class ModelResponseHandler extends AsyncHttpResponseHandler {
        int seriesId;

        public ModelResponseHandler(int series_id) {
            seriesId = series_id;
        }

        @Override
        public void onSuccess(String content) {
            super.onSuccess(content);
            LogUtil.e("content=" + content);
            ModelRespone response = new Gson().fromJson(content, ModelRespone.class);
            if (response == null) {// 解析数据出错
                error("获取车型数据出错 content=" + content);
                return;
            }

            if (response.errorCode != 0) {// 返回错误
                error("获取车型数据出错 code=" + response.errorCode + " : " + response.errorMessge);
                return;
            }

            // "id": "337905",
            // "model_year": "2015",
            // "text":
            // "\u5e15\u8428\u7279 1.8TSI \u53cc\u79bb\u5408 30\u5468\u5e74\u7eaa\u5ff5\u7248"
            // 帕萨特 1.8TSI 双离合 30周年纪念版

            CarModel[] models = response.data;
            for (CarModel model : models) {
                model.setSeriesId(seriesId);
                modelList.add(model);
            }

        }

        @Override
        public void onFailure(HttpFailureException error) {
            super.onFailure(error);
            error("获取车型数据出错 error=" + error.getMessage());
        }

        @Override
        public void onFailure(HttpFailureException error, String content) {
            super.onFailure(error, content);
            error("获取车型数据出错 error=" + error.getMessage() + " " + content);
        }

    }

    /**
     * 得到车型
     */
    private static void getModel(final int seriesId) {
        String url = getUrl(URL_MODEL, "&series_id=" + seriesId);
        baseAPI.post(url, null, new ModelResponseHandler(seriesId));
    }

    /**
     * 获取Token监听
     *
     * @author "叶晋"
     */
    interface GetTokenListener {
        public void onSuccess();
    }

    /**
     * 获取token
     * 需要权限
     * <uses-permission android:name="android.permission.INTERNET" />
       <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     */
    private static void getToken(final GetTokenListener getTokenListener) {
        String url = getUrl(URL_GET_TOKEN, "");
        LogUtil.e(url);
        baseAPI.post(url, null, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                LogUtil.e("content=" + content);
                TokenRespone response = new Gson().fromJson(content, TokenRespone.class);

                if (response.errorCode == 0) {// 正确返回
                    token = response.data;
                    if (getTokenListener != null)
                        getTokenListener.onSuccess();
                } else {
                    error("获取token出错 code=" + response.errorCode + " : " + response.errorMessge);
                }
            }

            @Override
            public void onFailure(HttpFailureException error) {
                super.onFailure(error);
                error("获取token出错 error=" + error.getMessage());
            }

            @Override
            public void onFailure(HttpFailureException error, String content) {
                super.onFailure(error, content);
                error("获取token出错 error=" + error.getMessage() + " " + content);
            }

        });
    }

    /**
     * 显示更新车型库对话框
     *
     * @param context
     */
    private static void showUpdateDbDialog(Context context) {
        // if (dialog == null) {
        dialog = new ProgressDialog(context);
        dialog.setTitle("更新车型库");
        dialog.setMessage("车型库更新中，请稍候...");
        dialog.setCancelable(false);
        // }
        dialog.show();
    }

    private static void dismissProgressDialog() {
        if (dialog != null)
            dialog.dismiss();
    }
//
//    /**
//     * 通过VIN获取车辆信息
//     *
//     * @param context
//     * @param vin
//     * @param listener
//     */
//    public static void getVin(Context context, String vin, CarVinListener listener) {
//
////        api = Api.getInstance();
//////        showVinDialog(context);
////        new Thread(new GetVinRunnable(vin, listener)).start();
//
//        Request req = new SubmitRequest(params, SUBMIT_URL,
//                new Response.Listener<JsonObject>() {
//                    @Override
//                    public void onResponse(JsonObject response) {
//                        ProgressDialogUtil.dismissProgressDlg();
//                        T.showShort(, "上传成功");
//                        validateCarResult();
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                ProgressDialogUtil.dismissProgressDlg();
//                T.showShort(MainActivity.this, "上传失败：" + error.getMessage());
//            }
//        });
//        ProgressDialogUtil.showProgressDlg(this, "上传车检报告");
//        addQueue(req);
//    }
//
//    /**
//     * 通过VIN获取车型信息
//     *
//     *
//     * @param vin
//     */
//    private static void getVin(String vin, final CarVinListener listener) {
//
//        String url = getUrl(URL_VIN, "&vin=" + vin);
//
//        L.w("url=" + url);
//        // api.post(url);
//        api.post(url, null, new AsyncHttpResponseHandler() {
//
//            @Override
//            public void onSuccess(String content) {
//                super.onSuccess(content);
//                L.w("content=" + content);
//                // pu.putLong(KEY_TIME, System.currentTimeMillis());
//
//                // dismissProgressDialog();
//                // if (listener != null)
//                // listener.onSuccess(content);
//
//                try {
//                    VinRespone response = new Gson().fromJson(content, VinRespone.class);
//                    if (response.errorCode == 0) {// 正确返回
//                        L.w("response.errorCode = 0");
//                        dismissProgressDialog();
//                        ToastUtil.showToastLong("获取VIN车辆信息成功");
//                        L.w("content=" + content);
//                        if (listener != null)
//                            listener.onSuccess(response.data);
//
//                    } else {
//                        L.w("response.errorCode = " + response.errorCode);
//                        error("获取车辆信息失败 code=" + response.errorCode + " : " + response.errorMessge);
//
//                        // if (listener != null)
//                        // listener.onFail();
//                    }
//                } catch (Exception e) {
//                    ErrorResponse response = new Gson().fromJson(content, ErrorResponse.class);
//
//                    L.w("response.errorCode = " + response.errorCode);
//                    error("获取车辆信息失败 code=" + response.errorCode + " : " + response.errorMessge);
//
//                    // if (listener != null)
//                    // listener.onFail();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpFailureException error) {
//                super.onFailure(error);
//                error("获取车辆信息失败  error=" + error.getMessage());
//                // if (listener != null)
//                // listener.onFail();
//            }
//
//            @Override
//            public void onFailure(HttpFailureException error, String content) {
//                super.onFailure(error, content);
//
//                error("获取车辆信息失败 error=" + error.getMessage() + " " + content);
//                // if (listener != null)
//                // listener.onFail();
//            }
//
//        });
//
//    }


}

